#include "staticlinklist.h"

/*space[0].cur is head node, "0" is null pointer*/
Status InitList(StaticLinkList space)
{
    int i;
    for (i = 0;  i < MAXSIZE - 1; i++)
    {
        space[i].curr = i + 1;
    }

    space[MAXSIZE - 1].curr = 0;
    return OK;
}

/*return 0, or index of element*/
int Malloc_StaticLinkList(StaticLinkList space)
{
    int i = space[0].curr;
    if (space[0].curr)
    {
        space[0].curr = space[i].curr;
    }

    return i;
}


/*insert element before index */
Status StaticLinkListInsert(StaticLinkList L, int i, ElemType e)
{
    int tmp, cur,l;
    cur = MAXSIZE - 1;
    if (i < l || i > StaticLinkListLength(L) + 1)
    {
        return ERROR;
    }

    tmp = Malloc_StaticLinkList(L);
    if (tmp)
    {
        L[tmp].data = e;
        for (l = 1; l <= i - 1; l++)
        {
            cur = L[cur].curr;
        }
        L[tmp].curr = L[cur].curr;
        L[cur].curr = tmp;
        return OK;
    }
    return ERROR;
}

/*Delete the index element*/
Status StaticLinklistDelete(StaticLinkList L, int i)
{
    int tmp, cur;
    if (i < 1 || i > StaticLinkListLength(L))
    {
        return ERROR;
    }
    cur = MAXSIZE - 1;
    for (tmp = 1; tmp <= i - 1; tmp++)
    {
        cur = L[cur].curr;
    }

    tmp = L[cur].curr;
    L[cur].curr = L[tmp].curr;
    Free_StaticLinklist(L, tmp);
    return OK;
}


/*collect index k node to static linklist*/
void Free_StaticLinklist(StaticLinkList space, int k)
{
    space[k].curr = space[0].curr;
    space[0].curr = k;
}

/*return Count of elements*/
int StaticLinkListLength(StaticLinkList L)
{
    int cnt = 0;
    int i = L[MAXSIZE - 1].curr;
    while (i)
    {
        i = L[i].curr;
        cnt++;
    }
    return cnt;
}